"use strict";

import Vue from 'vue';
import axios from "axios";

function get_url_extension( url ) {
  return url.split(/[#?]/)[0].split('.').pop().trim();
}

// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// const baseURL = 'http://localhost:9096';
// const imgHost = 'http://localhost:9096';
// const baseURL = 'http://psy-server.cd2c19dacf66e4107927b899d29ced135.cn-beijing.alicontainer.com';
// const imgURL = 'http://psy-server.cd2c19dacf66e4107927b899d29ced135.cn-beijing.alicontainer.com/images/';
const  baseURL = "http://psy-data.cy66688.cn";
const  imgHost = "http://local-img.cy66688.cn";

let config = {
  baseURL: baseURL,
  proxyImage: (URL)=>{
    let ext = get_url_extension(URL);
    if(ext) {
      let file = URL.substring(0, URL.lastIndexOf("."+ext));
      file = (window.btoa(file)).replace(/=+?$/, "");
      return imgHost + "/proxy-images/" + file + "." + ext;
    } else {
      return URL
    }
  },
  timeout: 60 * 1000, // Timeout
  // withCredentials: true, // Check cross-site Access-Control
};

const _axios = axios.create(config);

_axios.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  function(response) {
    // Do something with response data
    return response;
  },
  function(error) {
    // Do something with response error
    return Promise.reject(error);
  }
);

Plugin.install = function(Vue) {
  Vue.axios = _axios;
  window.axios = _axios;
  Object.defineProperties(Vue.prototype, {
    axios: {
      get() {
        return _axios;
      }
    },
    $axios: {
      get() {
        return _axios;
      }
    },
  });
};

Vue.use(Plugin);

export default Plugin;
